/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.registration.gui.security;

import javax.ejb.Stateful;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.security.auth.login.LoginException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author miglie
 */
@ManagedBean(name="loginBean")
@RequestScoped
@Stateful
public class LoginBean {

    private String usersname;
    private String password;

    public LoginBean() {
    }

    public String getUsersname() {
        System.out.println("GET ["+this.usersname+"]");
        return this.usersname;
    }

    public void setUsersname(String usersname) {
        this.usersname = usersname;
        System.out.println("SET USERSNAME ["+this.usersname+"] ["+usersname+"]");

    }  

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String login() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        try {
            request.login(this.usersname, this.password);
        } catch (ServletException e) {
            context.addMessage(null, new FacesMessage("Login failed."));
            return "login";
        }
        return "/home?faces-redirect=true";
    }
    public String logout() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        request.getSession().invalidate();
        return "/login?faces-redirect=true";
    }
}
